﻿// **********************************************************************
//
// Author: KingSley
// Email:3268374537@qq.com
// Created:	2018/8/1   09:30
// Introduce: Json文件的序列化处理
//
// **********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;

namespace KingSley
{
    public class JsonUtility
    {
        public static JsonObject Deserialize(string json)
        {
            if (string.IsNullOrEmpty(json.Trim()))
            {
                return null;
            }

            return JsonParser.Parse(json);
        }
        public static string Serialize(object obj)
        {
            return JsonSerializer.Serialize(obj);
        }


    }

    [System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
    public sealed class JsonIgnoreAttribute : System.Attribute { }

    public sealed class JsonParser : IDisposable
    {
        const string WORD_BREAK = "{}[],:\"";

        public static bool IsWordBreak(char c)
        {
            return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1;
        }

        enum TOKEN
        {
            NONE,
            CURLY_OPEN,
            CURLY_CLOSE,
            SQUARED_OPEN,
            SQUARED_CLOSE,
            COLON,
            COMMA,
            STRING,
            NUMBER,
            TRUE,
            FALSE,
            NULL
        };

        StringReader json;

        JsonParser(string jsonString)
        {
            json = new StringReader(jsonString);
        }

        public static JsonObject Parse(string jsonString)
        {
            using (var instance = new JsonParser(jsonString))
            {
                return instance.ParseValue();
            }
        }

        public void Dispose()
        {
            json.Dispose();
            json = null;
        }

        JsonObject ParseObject()
        {
            Dictionary<string, JsonObject> table = new Dictionary<string, JsonObject>();
            
            json.Read();
            
            while (true)
            {
                switch (NextToken)
                {
                    case TOKEN.NONE:
                        return null;
                    case TOKEN.COMMA:
                        continue;
                    case TOKEN.CURLY_CLOSE:
                        return new JsonObject(table);
                    default:
                        // name
                        string name = ParseString();
                        if (name == null)
                        {
                            return null;
                        }
                        if (NextToken != TOKEN.COLON)
                        {
                            return null;
                        }
                        json.Read();
                        table[name] = ParseValue();
                        break;
                }
            }
        }

        JsonObject ParseArray()
        {
            List<JsonObject> array = new List<JsonObject>();
            
            json.Read();
            var parsing = true;
            while (parsing)
            {
                TOKEN nextToken = NextToken;

                switch (nextToken)
                {
                    case TOKEN.NONE:
                        return null;
                    case TOKEN.COMMA:
                        continue;
                    case TOKEN.SQUARED_CLOSE:
                        parsing = false;
                        break;
                    default:
                        var val = ParseByToken(nextToken);

                        array.Add(val);
                        break;
                }
            }

            return new JsonObject(array);
        }

        JsonObject ParseValue()
        {
            TOKEN nextToken = NextToken;
            return ParseByToken(nextToken);
        }

        JsonObject ParseByToken(TOKEN token)
        {
            switch (token)
            {
                case TOKEN.STRING:
                    return ParseStringObj();
                case TOKEN.NUMBER:
                    return ParseNumber();
                case TOKEN.CURLY_OPEN:
                    return ParseObject();
                case TOKEN.SQUARED_OPEN:
                    return ParseArray();
                case TOKEN.TRUE:
                    return new JsonObject(true);
                case TOKEN.FALSE:
                    return new JsonObject(false);
                case TOKEN.NULL:
                    return new JsonObject(null);
                default:
                    return null;
            }
        }

        JsonObject ParseStringObj()
        {
            return new JsonObject(ParseString());
        }

        string ParseString()
        {
            StringBuilder s = new StringBuilder();
            char c;

            // ditch opening quote
            json.Read();

            bool parsing = true;
            while (parsing)
            {

                if (json.Peek() == -1)
                {
                    parsing = false;
                    break;
                }

                c = NextChar;
                switch (c)
                {
                    case '"':
                        parsing = false;
                        break;
                    case '\\':
                        if (json.Peek() == -1)
                        {
                            parsing = false;
                            break;
                        }

                        c = NextChar;
                        switch (c)
                        {
                            case '"':
                            case '\\':
                            case '/':
                                s.Append(c);
                                break;
                            case 'b':
                                s.Append('\b');
                                break;
                            case 'f':
                                s.Append('\f');
                                break;
                            case 'n':
                                s.Append('\n');
                                break;
                            case 'r':
                                s.Append('\r');
                                break;
                            case 't':
                                s.Append('\t');
                                break;
                            case 'u':
                                var hex = new char[4];

                                for (int i = 0; i < 4; i++)
                                {
                                    hex[i] = NextChar;
                                }

                                s.Append((char)Convert.ToInt32(new string(hex), 16));
                                break;
                        }
                        break;
                    default:
                        s.Append(c);
                        break;
                }
            }
            return s.ToString();
        }

        JsonObject ParseNumber()
        {
            string number = NextWord;
            return new JsonObject(number) { isNumber = true };
        }

        void EatWhitespace()
        {
            while (Char.IsWhiteSpace(PeekChar))
            {
                json.Read();

                if (json.Peek() == -1)
                {
                    break;
                }
            }
        }

        char PeekChar
        {
            get
            {
                return Convert.ToChar(json.Peek());
            }
        }

        char NextChar
        {
            get
            {
                return Convert.ToChar(json.Read());
            }
        }

        string NextWord
        {
            get
            {
                StringBuilder word = new StringBuilder();

                while (!IsWordBreak(PeekChar))
                {
                    word.Append(NextChar);

                    if (json.Peek() == -1)
                    {
                        break;
                    }
                }

                return word.ToString();
            }
        }

        TOKEN NextToken
        {
            get
            {
                EatWhitespace();

                if (json.Peek() == -1)
                {
                    return TOKEN.NONE;
                }

                switch (PeekChar)
                {
                    case '{':
                        return TOKEN.CURLY_OPEN;
                    case '}':
                        json.Read();
                        return TOKEN.CURLY_CLOSE;
                    case '[':
                        return TOKEN.SQUARED_OPEN;
                    case ']':
                        json.Read();
                        return TOKEN.SQUARED_CLOSE;
                    case ',':
                        json.Read();
                        return TOKEN.COMMA;
                    case '"':
                        return TOKEN.STRING;
                    case ':':
                        return TOKEN.COLON;
                    case '0':
                    case '1':
                    case '2':
                    case '3':
                    case '4':
                    case '5':
                    case '6':
                    case '7':
                    case '8':
                    case '9':
                    case '-':
                        return TOKEN.NUMBER;
                }

                switch (NextWord)
                {
                    case "false":
                        return TOKEN.FALSE;
                    case "true":
                        return TOKEN.TRUE;
                    case "null":
                        return TOKEN.NULL;
                }

                return TOKEN.NONE;
            }
        }
    }

    public sealed class JsonSerializer
    {
        StringBuilder builder;

        public static readonly Type ignoreAttrType = typeof(JsonIgnoreAttribute);
        public static readonly Type bbJsonObjType = typeof(JsonObject);

        JsonSerializer()
        {
            builder = new StringBuilder();
        }

        public static string Serialize(object obj)
        {
            var instance = new JsonSerializer();

            instance.SerializeValue(obj);

            return instance.builder.ToString();
        }

        void SerializeValue(object value)
        {
            IList asList;
            IDictionary asDict;
            string asStr;
            JsonObject jsonObj;

            if ((jsonObj = value as JsonObject) != null)
            {
                if (jsonObj.isNumber)
                    SerializeString(jsonObj.Raw as string, true);
                else
                    SerializeValue(jsonObj.Raw);
            }
            else if (value == null)
            {
                builder.Append("null");
            }
            else if ((asStr = value as string) != null)
            {
                SerializeString(asStr);
            }
            else if (value is bool)
            {
                builder.Append((bool)value ? "true" : "false");
            }
            else if ((asList = value as IList) != null)
            {
                SerializeArray(asList);
            }
            else if ((asDict = value as IDictionary) != null)
            {
                SerializeObject(asDict);
            }
            else if (value is char)
            {
                SerializeString(new string((char)value, 1));
            }
            else
            {
                SerializeOther(value);
            }
        }

        void SerializeObject(IDictionary obj)
        {
            bool first = true;

            builder.Append('{');

            foreach (object e in obj.Keys)
            {
                if (!first)
                {
                    builder.Append(',');
                }

                SerializeString(e.ToString());
                builder.Append(':');

                SerializeValue(obj[e]);

                first = false;
            }

            builder.Append('}');
        }

        void SerializeArray(IList anArray)
        {
            builder.Append('[');

            bool first = true;

            foreach (object obj in anArray)
            {
                if (!first)
                {
                    builder.Append(',');
                }

                SerializeValue(obj);

                first = false;
            }

            builder.Append(']');
        }

        void SerializeString(string str, bool isNumber = false)
        {
            if (!isNumber)
                builder.Append('\"');

            char[] charArray = str.ToCharArray();
            foreach (var c in charArray)
            {
                switch (c)
                {
                    case '"':
                        builder.Append("\\\"");
                        break;
                    case '\\':
                        builder.Append("\\\\");
                        break;
                    case '\b':
                        builder.Append("\\b");
                        break;
                    case '\f':
                        builder.Append("\\f");
                        break;
                    case '\n':
                        builder.Append("\\n");
                        break;
                    case '\r':
                        builder.Append("\\r");
                        break;
                    case '\t':
                        builder.Append("\\t");
                        break;
                    default:
                        int codepoint = Convert.ToInt32(c);
                        if ((codepoint >= 32) && (codepoint <= 126))
                        {
                            builder.Append(c);
                        }
                        else
                        {
                            builder.Append("\\u");
                            builder.Append(codepoint.ToString("x4"));
                        }
                        break;
                }
            }
            if (!isNumber)
                builder.Append('\"');
        }

        void TrySerializeObject(object o)
        {
            var t = o.GetType();
            if (bbJsonObjType.IsAssignableFrom(t))
            {
                var raw = (o as JsonObject).Raw;
                o = raw;
                t = o.GetType();
            }
            if (t.IsEnum)
            {
                this.SerializeValue((int)o);
            }
            else if (t == typeof(IEnumerable) || t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            {
                var arr = new ArrayList();
                foreach (var item in o as IEnumerable)
                {
                    arr.Add(item);
                }
                SerializeArray(arr);
            }
            else
            {
                var fields = t.GetFields();
                var props = t.GetProperties();
                var dict = new Dictionary<string, object>();
                for (var i = 0; i < fields.Length; i++)
                {
                    if (fields[i].GetCustomAttributes(ignoreAttrType, true).Length > 0)
                        continue;
                    try
                    {
                        dict.Add(fields[i].Name, fields[i].GetValue(o));
                    }
                    catch (Exception ex)
                    {
                        Debug.LogException(ex);
                    }
                }
                for (var i = 0; i < props.Length; i++)
                {
                    if (!props[i].CanWrite || !props[i].CanRead)
                        continue;
                    if (props[i].GetCustomAttributes(ignoreAttrType, true).Length > 0)
                        continue;
                    try
                    {
                        dict.Add(props[i].Name, props[i].GetValue(o, null));
                    }
                    catch (Exception ex)
                    {
                        Debug.LogException(ex);
                    }
                }

                SerializeObject(dict);
            }
        }

        void SerializeOther(object value)
        {
            if (value is float)
            {
                builder.Append(((float)value).ToString("R"));
            }
            else if (value is int
                     || value is uint
                     || value is long
                     || value is sbyte
                     || value is byte
                     || value is short
                     || value is ushort
                     || value is ulong)
            {
                builder.Append(value);
            }
            else if (value is double
                     || value is decimal)
            {
                builder.Append(Convert.ToDouble(value).ToString("R"));
            }
            else
            {
                TrySerializeObject(value);
            }
        }
    }

    public class JsonObject
    {
        public JsonObject(object obj)
        {
            _obj = obj;
        }

        private object _obj;

        public object Raw { get { return _obj; } }

        public bool isNumber;

        public T To<T>()
        {
            try
            {
                return (T)To(typeof(T));
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                return default(T);
            }
        }

        public bool IsList
        {
            get { return Raw is IEnumerable; }
        }

        public IList<JsonObject> AsList()
        {
            return Raw as IList<JsonObject>;
        }

        public IList<T> AsList<T>()
        {
            var l = Raw as IList<JsonObject>;
            return l.Select(obj => obj.To<T>()).ToList();
        }

        public JsonObject[] AsArray()
        {
            return AsList().ToArray();
        }

        public T[] AsArray<T>()
        {
            var l = Raw as IList<JsonObject>;
            return l.Select(obj => obj.To<T>()).ToArray();
        }

        public bool IsDictionary
        {
            get { return Raw is IDictionary; }
        }

        public IDictionary<string, JsonObject> AsDictionary()
        {
            return Raw as Dictionary<string, JsonObject>;
        }

        public bool AsBool()
        {
            if (Raw is bool)
                return (bool)Raw;
            return Convert.ToBoolean(Raw);
        }

        public int AsInt()
        {
            int val;
            if (int.TryParse(_obj as string, out val))
                return val;
            return 0;
        }

        public float AsFloat()
        {
            float val;
            if (float.TryParse(_obj as string, out val))
                return val;
            return 0;
        }

        public string AsString()
        {
            if (Raw is string)
                return (string)Raw;
            if (Raw != null)
                return Raw.ToString();
            return null;
        }

        public object To(Type t)
        {
            #region C# Builtin Types Convert
            if (t == typeof(bool))
            {
                if (_obj is bool)
                    return _obj;
                else return Convert.ToBoolean(_obj);
            }
            if (t == typeof(byte))
            {
                byte val;
                if (byte.TryParse(_obj as string, out val))
                    return val;
                return 0;
            }
            else if (t == typeof(sbyte))
            {
                sbyte val;
                if (sbyte.TryParse(_obj as string, out val))
                    return val;
                return 0;
            }
            else if (t == typeof(char))
            {
                char val;
                if (char.TryParse(_obj as string, out val))
                    return val;
                return 0;
            }
            else if (t == typeof(decimal))
            {
                decimal val;
                if (decimal.TryParse(_obj as string, out val))
                    return val;
                return 0;
            }
            else if (t == typeof(double))
            {
                double val;
                if (double.TryParse(_obj as string, out val))
                    return val;
                return 0;
            }
            else if (t == typeof(float))
            {
                return AsFloat();
            }
            else if (t == typeof(int))
            {
                return AsInt();
            }
            else if (t == typeof(uint))
            {
                uint val;
                if (uint.TryParse(_obj as string, out val))
                    return val;
                return 0;
            }
            else if (t == typeof(long))
            {
                long val;
                if (long.TryParse(_obj as string, out val))
                    return val;
                return 0;
            }
            else if (t == typeof(ulong))
            {
                ulong val;
                if (ulong.TryParse(_obj as string, out val))
                    return val;
                return 0;
            }
            else if (t == typeof(short))
            {
                short val;
                if (short.TryParse(_obj as string, out val))
                    return val;
                return 0;
            }
            else if (t == typeof(ushort))
            {
                ushort val;
                if (ushort.TryParse(_obj as string, out val))
                    return val;
                return 0;
            }
            else if (t == typeof(string))
            {
                return AsString();
            }
            else if (t == typeof(object))
            {
                return _obj;
            }
            #endregion
            if (t.IsEnum)
            {
                int val;
                if (int.TryParse(_obj as string, out val))
                    return val;
                else
                    return Enum.Parse(t, _obj.ToString());
            }
            else if (JsonSerializer.bbJsonObjType.IsAssignableFrom(t))
            {
                return (_obj as JsonObject).To(t);
            }
            else if (t.IsArray)
            {
                if (Raw is IList<JsonObject>)
                {
                    var et = t.GetElementType();
                    var list = Raw as IList<JsonObject>;
                    var arr = Array.CreateInstance(et, list.Count);
                    for (var i = 0; i < list.Count; i++)
                    {
                        arr.SetValue(list[i].To(et), i);
                    }
                    return arr;
                }
            }
            else if (IsSupportedListType(t))
            {
                if (Raw is IList<JsonObject>)
                {
                    var et = typeof(object);
                    if (t.IsGenericType) et = t.GetGenericArguments()[0];
                    var list = Raw as IList<JsonObject>;
                    var lt = typeof(List<>);
                    lt = lt.MakeGenericType(new[] { et });
                    try
                    {
                        var result = Activator.CreateInstance(lt) as IList;
                        for (var i = 0; i < list.Count; i++)
                        {
                            result.Add(list[i].To(et));
                        }
                        return result;
                    }
                    catch (System.Exception ex)
                    {
                        Debug.LogException(ex);
                    }
                }
            }
            else if (IsTypeDictionary(t))
            {
                if (Raw is IDictionary<string, JsonObject>)
                {
                    var et = typeof(object);
                    if (t.IsGenericType) et = t.GetGenericArguments()[1];
                    var dict = Raw as IDictionary<string, JsonObject>;
                    var dt = typeof(Dictionary<,>);
                    dt = dt.MakeGenericType(new[] { typeof(string), et });
                    try
                    {
                        var result = Activator.CreateInstance(dt) as IDictionary;
                        foreach (var kvp in dict)
                        {
                            result.Add(kvp.Key, kvp.Value.To(et));
                        }
                        return result;
                    }
                    catch (System.Exception ex)
                    {
                        Debug.LogException(ex);
                    }
                }
            }
            else if (Raw is IDictionary<string, JsonObject>)
            {
                var dict = Raw as IDictionary<string, JsonObject>;
                var ins = t.Assembly.CreateInstance(t.FullName);
                var fields = t.GetFields();
                foreach (var f in fields)
                {
                    if (f.GetCustomAttributes(JsonSerializer.ignoreAttrType, true).Length > 0)
                        continue;
                    if (dict[f.Name] == null)
                        continue;
                    f.SetValue(ins, dict[f.Name].To(f.FieldType));
                }
                var props = t.GetProperties();
                foreach (var p in props)
                {
                    if (!p.CanRead || !p.CanWrite)
                        continue;
                    if (p.GetCustomAttributes(JsonSerializer.ignoreAttrType, true).Length > 0)
                        continue;
                    var name = p.Name;
                    if (dict[p.Name] == null)
                        name = FirstLetterToLower(name);
                    if (dict[name] == null)
                        continue;
                    p.SetValue(ins, dict[name].To(p.PropertyType), null);
                }
                return ins;
            }
            return null;
        }

        private string FirstLetterToLower(string name)
        {
            return name[0].ToString().ToLower() + name.Substring(1);
        }

        private bool IsSupportedListType(Type t)
        {
            if (t == typeof(IEnumerable) || t == typeof(IList) || t == typeof(ArrayList))
                return true;
            if (t.IsGenericType)
                return t.GetGenericTypeDefinition() == typeof(IList<>) || t.GetGenericTypeDefinition() == typeof(IEnumerable<>) || t.GetGenericTypeDefinition() == typeof(List<>);

            return false;
        }

        private bool IsTypeDictionary(Type t)
        {
            if (t == typeof(IDictionary))
                return true;
            if (t.IsGenericType)
            {
                if (t.GetGenericTypeDefinition() == typeof(Dictionary<,>))
                {
                    return t.GetGenericArguments()[0] == typeof(string);
                }
                return false;
            }
            return false;
        }
    }
}